package org.gjw.util;

/** JWT 生成工具
 * 生成的token中包括
 *  |-  sub 用户名称
 *  |-  exp 过期时间
 *  |-  genTime 生成时间
 * @author guojunwang
 * @date 2021-06-25 23:56
 */

import io.jsonwebtoken.*;
import org.gjw.bean.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(JwtUtil.class);

    //token生成日期
    private static final String CLAIM_KEY_GENTIME = "genTime";
    private static final String CLAIM_KEY_ID = "tokenId";

    //加密密钥
    private final String secret="B7r%MIBrYCxw91NG471i1Ur2hWVRI&tcBPXd9";

//    @Value("${jwt.expire}")
    private Long expiration = 1000L;

    /**
     * 根据负责生成JWT的token
     */
    private String generateToken(Map<String, Object> claims,Date expireDate) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 从token中获取JWT中的负载
     */
    private Claims getClaimsFromToken(String token) {

        Claims claims = null;
        try {
            //解析token
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            System.out.println("token无效-->");
        }

        return claims;
    }

    /**
     * 从token中获取登录用户名
     */
    public String getUserNameFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims==null ? "" : claims.getSubject();
    }

    /**
     * 从token中获取信息 如 CLAIM_KEY_GENTIME , CLAIM_KEY_ID
     */
    public  String getInfoFromToken(String token,String key){
        Claims claims = getClaimsFromToken(token);
        return claims==null ? "" : claims.get(key).toString();
    }


    /**
     * 验证token是否还有效
     *
     * @param token       客户端传入的token
     * @param sysUser 从数据库中查询出来的用户信息
     */
    public boolean validateToken(String token, SysUser sysUser) {
        if(sysUser == null ) return false;
        String username = getUserNameFromToken(token);
        return username.equals(sysUser.getUsername()) && !isTokenExpired(token);
    }

    /**
     * 判断token是否已经失效
     */
    private boolean isTokenExpired(String token) {
        Date expiredDate = getExpiredDateFromToken(token);
        return expiredDate.before(new Date());
    }

    /**
     * 获取 token 的过期时间
     */
    private Date getExpiredDateFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.getExpiration();
    }

    /**
     * 根据用户信息生成token
     */
    public String generateToken(SysUser sysUser) {
        return generateToken(sysUser,genExpireDate());
    }

    /**
     * 根据用户信息生成token
     */
    public String generateToken(SysUser sysUser,Date date) {
        //放入 claims
        Map<String, Object> claims = new HashMap<>();
        //放入一些信息,可以通过 getInfoFromToken()方法取出
        claims.put(Claims.SUBJECT, sysUser.getUsername());
        claims.put(CLAIM_KEY_GENTIME, new Date());
        claims.put(CLAIM_KEY_ID, sysUser.getId());
        return generateToken(claims,date);
    }



    /**
     * 判断token是否可以被刷新
     */
    public boolean canRefresh(String token) {
        return !isTokenExpired(token);
    }

    /**
     * 刷新token
     */
    public String refreshToken(String token) {

        Claims claims = getClaimsFromToken(token);
        claims.put(CLAIM_KEY_GENTIME, new Date());

        return generateToken( claims,genExpireDate() );
    }



    private Date genExpireDate(){
        return  new Date(System.currentTimeMillis() + expiration * 1000);
    }

}